﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;

namespace LogWatcher.Common
{
    public static class HistoryFileManager
    {
        private class Comparer : IEqualityComparer<String>
        {
            public bool Equals(string x, string y)
            {
                if (x == null && y == null)
                    return true;
                if ((x == null) || (y == null))
                    return false;

                return x.ToLower() == y.ToLower();
            }

            public int GetHashCode(string obj)
            {
                return obj == null ? 0 : obj.ToLower().GetHashCode();
            }
        }

        private static readonly String FILE = AppDomain.CurrentDomain.BaseDirectory + "\\history.dat";

        public static List<String> LoadHistoryFileList()
        {
            try
            {
                return File.ReadAllLines(FILE).ToList();
            }
            catch (IOException e)
            {
                Console.WriteLine("Error: " + e.Message);
                Console.WriteLine("Use default!");
                return new List<string>();
            }
        }

        public static void AddFileToHistoryFileList(String file)
        {
            if (!File.Exists(FILE) || !File.ReadAllLines(FILE).Contains(file, new Comparer()))
            {
                using (StreamWriter writer = new StreamWriter(new FileStream(FILE, FileMode.Append)))
                {
                    writer.WriteLine(file);
                }
            }
        }

        public static void ClearHistory()
        {
            if (File.Exists(FILE))
            {
                File.Delete(FILE);
            }
        }
    }
}
